<?php

namespace App\HttpController\Admin;

use App\Common\Tools;
use EasySwoole\Utility\Random;
use EasySwoole\EasySwoole\Config;

use App\Validate\Upload as UploadValidate;

class Upload extends Base
{
    function index()
    {
        $file = $this->request()->getUploadedFile('file');
        if (($result = (new UploadValidate)->validate(['file' => $file])) !== true) {
            Tools::json($this->response(), [
                'errno'   => 1,
                'message' => $result,
            ]);
            return false;
        }
        if ($file->getSize() > 3145728) {
            Tools::json($this->response(), [
                'errno'   => 1,
                'message' => '文件不能超过3M',
            ]);
        }
        $suffix = explode('.', $file->getClientFilename())[1];
        $name   = Random::makeUUIDV4();
        $path   = Config::getInstance()->getConf('UPLOAD.path');
        $path  .= date('Y') . '/' . date('m') . '/' . date('d') . '/';
        if (!is_dir($path)) {
            mkdir($path, 0777, true);
        }
        $fileName = $path . $name . '.' . $suffix;
        $file->moveTo(EASYSWOOLE_ROOT . '/public' . $fileName);
        Tools::json($this->response(), [
            'errno' => 0,
            'data'  => [
                'url'  => $fileName,
                'alt'  => '',
                'href' => '',
            ],
        ]);
    }
}
